package com.fiberhome.nas.core.data.repository

import com.fiberhome.nas.core.model.entity.PhotoInfo
import com.fiberhome.nas.core.model.request.UploadRequest
import com.fiberhome.nas.core.model.response.ListData
import com.fiberhome.nas.core.model.response.NetworkResponse
import com.fiberhome.nas.core.model.response.UploadResult
import com.fiberhome.nas.core.network.datasource.photo.PhotoNetworkDataSource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject

/**
 * 照片相关仓库
 */
class PhotoRepository @Inject constructor(
    private val photoNetworkDataSource: PhotoNetworkDataSource
) {

    /**
     * 获取照片文件列表
     */
    fun getPhotoList(
        size: String,
        albumId: String? = null,
        sceneId: String? = null,
        peopleId: String? = null,
    ): Flow<NetworkResponse<ListData<PhotoInfo>>> = flow {
        val timeBucketsResponse =
            photoNetworkDataSource.getTimeBuckets(size, albumId, sceneId, peopleId)
        if (timeBucketsResponse.isSucceeded) {
            val allPhotos = mutableListOf<PhotoInfo>()
            timeBucketsResponse.data?.items?.forEach { timeBucket ->
                val photoListResponse = photoNetworkDataSource.getTimeBucket(
                    size,
                    timeBucket.timeBucket,
                    albumId = albumId,
                    sceneId = sceneId,
                    peopleId = peopleId
                )
                if (photoListResponse.isSucceeded) {
                    photoListResponse.data?.items?.let { allPhotos.addAll(it) }
                } else {
                    emit(photoListResponse)
                    return@forEach
                }
            }
            emit(
                NetworkResponse(ListData<PhotoInfo>(items = allPhotos))
            )
        } else {
            emit(
                NetworkResponse(
                    code = timeBucketsResponse.code,
                    message = timeBucketsResponse.message
                )
            )
        }
    }.flowOn(Dispatchers.IO)

    /**
     * 上传文件
     */
    fun uploadPhoto(uploadRequest: UploadRequest): Flow<NetworkResponse<UploadResult>> = flow {
        val uploadResponse = photoNetworkDataSource.uploadPhoto(uploadRequest)
        emit(uploadResponse)
    }.flowOn(Dispatchers.IO)

}